﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Products.Specs;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.LuceneHelper;

namespace NopSolutions.NopCommerce.Web.Templates.Lucene
{
    public partial class LuceneOptions : BaseLuceneFilterableControl
    {
        private IList<Facet> _facets;

        #region Utilities

        public override void BindData(FilterEventArgs e)
        {
            _facets = e.Facets;

            if (_facets.Count > 1)
            {
                rptFilterByPSO.DataSource = e.Facets;
                rptFilterByPSO.DataBind();
            }
            else
            {
                Visible = false;
            }
        }

        //protected IList<SpecificationAttributeOptionValue> RemoveAllreadyFiltered(IList<Facet> facets, IList<SpecificationAttributeOption> currentlyFilterdOptions)
        //{
        //    var toRemove = new List<Facet>();
        //    foreach (var currentlyFilterdOption in currentlyFilterdOptions)
        //    {
        //        var termQuery = new TermQuery(new Term("sdf", ""));

        //    }
        //}

        protected string[] getAlreadyFilteredSpecsQueryStringParams()
        {
            var result = new List<string>();

            var reservedQueryStringParamsSplitted = new List<string>();
            if (!String.IsNullOrEmpty(this.ReservedQueryStringParams))
            {
                reservedQueryStringParamsSplitted = this.ReservedQueryStringParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }

            foreach (string qsp in HttpContext.Current.Request.QueryString)
            {
                if (!String.IsNullOrEmpty(qsp))
                {
                    string _qsp = qsp.ToLowerInvariant();
                    if (!reservedQueryStringParamsSplitted.Contains(_qsp))
                    {
                        if (!result.Contains(_qsp))
                            result.Add(_qsp);
                    }
                }
            }
            return result.ToArray();
        }

        protected string excludeQueryStringParams(string url)
        {
            if (!String.IsNullOrEmpty(this.ExcludedQueryStringParams))
            {
                string[] excludedQueryStringParamsSplitted = this.ExcludedQueryStringParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string exclude in excludedQueryStringParamsSplitted)
                {
                    url = CommonHelper.RemoveQueryString(url, exclude);
                }
            }

            return url;
        }

        private string lastSA = string.Empty;
        protected string addSpecificationAttribute()
        {
            //Get the data field value of interest for this row   
            string currentSA = Eval("SpecificationAttributeName").ToString();

            //See if there's been a change in value
            if (lastSA != currentSA)
            {
                lastSA = currentSA;
                return String.Format("<tr class=\"group\"><td>{0}</td></tr>", Server.HtmlEncode(currentSA));
            }
            else
            {
                return String.Empty;
            }
        }

        #endregion

        #region Handlers

        protected void rptFilterByPSO_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                var dataItem = e.Item.DataItem as Facet;
                var ddlOptions = e.Item.FindControl("ddlOptions") as DropDownList;
                if (ddlOptions != null && dataItem != null)
                {
                    ddlOptions.Attributes["specId"] = dataItem.Attribute.SpecificationAttributeId.ToString();
                    ddlOptions.DataSource = dataItem.Options;
                    ddlOptions.DataBind();
                    ddlOptions.SelectedIndexChanged += OptionSelected;
                }
            }
        }

        protected void OptionSelected(object sender, EventArgs e)
        {
            var dropDownList = sender as DropDownList;
            var optionId = 0;
            int.TryParse(dropDownList.SelectedValue, out optionId);
            if (optionId > 0)
            {
                var option = SpecificationAttributeManager.GetSpecificationAttributeOptionById(optionId);
                if (option != null)
                {
                    string url = CommonHelper.ModifyQueryString(CommonHelper.GetThisPageUrl(true), "attr" + option.SpecificationAttributeId.ToString() + "=" + option.SpecificationAttributeOptionId, null);
                    url = excludeQueryStringParams(url);
                    Response.Redirect(url);
                }
            }
        }

        protected void OptionDataBound(object sender, EventArgs e)
        {
            var ddl = sender as DropDownList;
            if (ddl != null)
            {
                var title = "All";
                var specificationAttributeId = 0;
                if (int.TryParse(ddl.Attributes["specId"], out specificationAttributeId))
                {
                    var attribute = _facets.SingleOrDefault(x => x.Attribute.SpecificationAttributeId == specificationAttributeId);
                    if (attribute != null)
                    {
                        title += " (" + attribute.Attribute.Total + ")";
                    }
                }
                ddl.Items.Insert(0, new ListItem(title, "0", true));
            }
        }

        #endregion

        #region Properties
        public string ExcludedQueryStringParams
        {
            get
            {
                if (ViewState["ExcludedQueryStringParams"] == null)
                    return string.Empty;
                else
                    return ((string)ViewState["ExcludedQueryStringParams"]).ToLowerInvariant();
            }
            set
            {
                ViewState["ExcludedQueryStringParams"] = value;
            }
        }

        public string ReservedQueryStringParams
        {
            get
            {
                if (ViewState["ReservedQueryStringParams"] == null)
                    return string.Empty;
                else
                    return ((string)ViewState["ReservedQueryStringParams"]).ToLowerInvariant();
            }
            set
            {
                ViewState["ReservedQueryStringParams"] = value;
            }
        }

        /// <summary>
        /// Category identifier
        /// </summary>
        public int CategoryId
        {
            get
            {
                if (ViewState["CategoryId"] == null)
                    return 0;
                else
                    return (int)ViewState["CategoryId"];
            }
            set
            {
                ViewState["CategoryId"] = value;
            }
        }
        #endregion
    }
}